import { dateTool } from "@/utils/dateTool";
import { reactive, toRefs } from "vue";
import {
	tryOnMounted,
	tryOnUnmounted,
	useTimeAgo as useTimeAgoCore,
	UseTimeAgoMessages,
} from "@vueuse/core";

export const useNow = (immediate = true) => {
	let timer: IntervalHandle;

	const state = reactive({
		year: 0,
		month: 0,
		week: "",
		day: 0,
		hour: "",
		minute: "",
		second: 0,
		meridiem: "",
	});

	const update = () => {
		const now = dateTool();

		const h = now.format("HH");
		const m = now.format("mm");
		const s = now.get("seconds");

		state.year = now.get("y");
		state.month = now.get("M") + 1;
		state.week = "星期" + ["日", "一", "二", "三", "四", "五", "六"][now.day()];
		state.day = now.get("date");
		state.hour = h;
		state.minute = m;
		state.second = s;

		state.meridiem = now.format("A");
	};

	function start() {
		update();
		clearInterval(timer);
		timer = setInterval(() => update(), 1000);
	}

	function stop() {
		clearInterval(timer);
	}

	tryOnMounted(() => {
		immediate && start();
	});

	tryOnUnmounted(() => {
		stop();
	});

	return {
		...toRefs(state),
		start,
		stop,
	};
};

const TIME_AGO_MESSAGE_MAP: UseTimeAgoMessages = {
	justNow: "刚刚",
	invalid: "无效时间",
	past: (n) => (n.match(/\d/) ? `${n}前` : n),
	future: (n) => (n.match(/\d/) ? `${n}后` : n),
	month: (n, past) => (n === 1 ? (past ? "上个月" : "下个月") : `${n} 个月`),
	year: (n, past) => (n === 1 ? (past ? "去年" : "明年") : `${n} 年`),
	day: (n, past) => (n === 1 ? (past ? "昨天" : "明天") : `${n} 天`),
	week: (n, past) => (n === 1 ? (past ? "上周" : "下周") : `${n} 周`),
	hour: (n) => `${n} 小时`,
	minute: (n) => `${n} 分钟`,
	second: (n) => `${n} 秒`,
};

export const useTimeAgo = (time: Date | number | string) => {
	const timeAgo = useTimeAgoCore(time, {
		messages: TIME_AGO_MESSAGE_MAP,
	});

	return timeAgo;
};
